import Vue from 'vue'
import Vuex from 'vuex'

import {
	chatProcessApi
} from '@/api'

Vue.use(Vuex);

const store = new Vuex.Store({
	state: {
		messages: [],
		// 聊天状态
		chatStatus: 0,
		task: null
	},
	getters: {
		getLastRobotMessage(state) {
			const targetIndex = state.messages.findLastIndex(item => item.role == 'assistant')
			return targetIndex == -1 ? null : state.messages[targetIndex]
		}
	},
	mutations: {
		START_MESSAGE(state, message) {
			state.messages.push(message)
		},
	},
	actions: {
		cancleRequest({
			state
		}) {
			state.task?.abort()
			state.chatStatus = 0
		},
		async startMessage({
			commit,
			getters,
			state
		}, prompt) {

			const apiForm = {
				prompt,
				options: {
					"parentMessageId": null
				},
				getTask: function(task) {
					// debugger  abort()
					state.task = task
				}
			}
			// 如果有上次聊条记录 需要拿到记录
			if (getters.getLastRobotMessage) {
				apiForm.options.parentMessageId = getters.getLastRobotMessage.id
			}
			commit("START_MESSAGE", {
				id: state.messages.length,
				role: "user",
				text: prompt
			})
			state.chatStatus = 1
			const result = await chatProcessApi(apiForm)
			// const tartgetIndex = result.toString().lastIndexOf('{"role":"assistant",')
			// const messageJson = JSON.parse(result.substr(tartgetIndex))
			// delete messageJson.detail
			// delete messageJson.delta
			state.chatStatus = 0
			commit("START_MESSAGE", {
				id: state.messages.length,
				role: "assistant",
				text: result.response
			})
		}
	},
})

export default store